package com.spzx.common.rabbitmq.service;

import com.spzx.common.rabbitmq.domain.SpzxCorrelationData;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

//封装mq生产者发送消息业务方法
@Component
public class RabbitmqService {
    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    RedisTemplate redisTemplate;

    public void sendMsg(String exchange , String routingKey , Object data, boolean retry , int retryLimit){
        //CorrelationData: 我们可以对它进行扩展 方便重试发送消息
        SpzxCorrelationData spzxCorrelationData = new SpzxCorrelationData();
        spzxCorrelationData.setData(data);
        spzxCorrelationData.setExchange(exchange);
        spzxCorrelationData.setRoutingKey(routingKey);
        spzxCorrelationData.setRetry(retry);
        spzxCorrelationData.setRetryLimit(retryLimit);
        //将spzxCorrelationData存到redis共享，使用spzxCorrelationData的id值作为键
        String retryKey = "spzx:mq:retry:"+spzxCorrelationData.getId();
        redisTemplate.opsForValue().set(retryKey,
                spzxCorrelationData ,600 , TimeUnit.SECONDS);

        rabbitTemplate.convertAndSend(spzxCorrelationData.getExchange(),
                spzxCorrelationData.getRoutingKey(),
                spzxCorrelationData.getData() , spzxCorrelationData);
    }
    //默认发送消息不重试
    public void sendMsg(String exchange , String routingKey , Object data){
        this.sendMsg(exchange,routingKey,data,false , 0);
    }
}
